import {
    actualMultiple,
    curIndex,
    currentNodeElements,
    drawData,
    hadaCanvas,
    historyDrawData, historyWindow, showHistoryWindow,
    showNodeElements
} from "./pageData";
import {NodeElement} from "./components/hada-canvas-poster/types";
import {ElMessageBox} from "element-plus";
import {computed, nextTick} from "vue";



/**
 * 绘制
 */
export const draw = async () => {
    if(hadaCanvas.value){
        //执行前执行函数
        let drawdata = copyObj(drawData.value);
        if(drawData.value.beforeCode){
            //匹配出方法内容
            drawdata.nodeElements = new Function('nodeElements',drawData.value.beforeCode)(drawdata.nodeElements);
        }
        await hadaCanvas.value.reDraw(drawdata);
    }
}


/**
 * 保存历史
 */
export const saveHistory = (name : string = '操作未命名') => {
    //历史保存如果撤销后继续操作需要清空当前历史后面的数据，重新记录新历史
    if(curIndex.value < historyDrawData.value.length - 1){
        historyDrawData.value.splice(curIndex.value + 1);
    }
    historyDrawData.value.push(copyObj({
        name,
        data: drawData.value
    }));
    console.log(historyDrawData.value.length,historyDrawData.value)
    //历史最大存储50步
    if(historyDrawData.value.length > 50){
        historyDrawData.value.shift();
    }
    curIndex.value = historyDrawData.value.length - 1;
    if(showHistoryWindow.value){
        nextTick(()=>{
            // @ts-ignore
            historyWindow.value.$el.scrollTop = historyWindow.value.$el.scrollHeight;
        })
    }
    console.log(historyWindow.value,'historyWindow.value')
    draw();
}

/**
 * 复制元素
 * @param node
 * @param index
 */
export const copyNode = (node : NodeElement,index) => {
    for (let j = 0; j < drawData.value.nodeElements.length; j++) {
        let element = drawData.value.nodeElements[j];
        if(node.id === element.id){
            const copyNode = JSON.parse(JSON.stringify(node));
            copyNode.id = Math.random().toString(36).slice(2);
            let showNode = showNodeElements.value.find(item=>item.id === node.id);
            copyNode.css.top += showNode.height;
            drawData.value.nodeElements.splice(j + 1,0,copyNode);
            break;
        }
    }
    saveHistory('复制元素');
}


function getCurrentNodeElementIndex() {
    if(currentNodeElements.value.length === 0){
        return -1;
    }

    for (let i = 0; i < drawData.value.nodeElements.length; i++) {
        if (drawData.value.nodeElements[i].id === currentNodeElements.value[0].id) {
            return i;
        }
    }
    return -1;
}

/**
 * 插入元素
 * @param type
 * @param content
 */
export const addNode = (type:string,content) => {

    let node = {
        id: Math.random().toString(36).slice(2),
        name: '',
        resourceType: type,
        ...content,
        css: {
            top: 0,
            left: 0,
            width: 100,
            height: 100,
            zIndex: 0,
        }
    };
    if(currentNodeElements.value.length > 0){
        node.css = copyObj(currentNodeElements.value[0].css);
        node.css.top += node.css.height;
    }
    const curIndex = getCurrentNodeElementIndex() + 1;

    if(type === 'text'){
        node.css.width = 0;
        node.css.height = 32;
        node.css.fontSize = 32;
        node.css.fontFamily = 'SimHei';
        node.css.color = '#FFFFFF';
        node.css.textOverflow = '...';
        drawData.value.nodeElements.splice(curIndex,0,node);
    }else if(type === 'icon'){
        node.css.width = 32;
        node.css.height = 32;
        node.css.color = '#FFFFFF';
        drawData.value.nodeElements.splice(curIndex,0,node);
    }else if(type === 'image'){
        drawData.value.nodeElements.splice(curIndex,0,node);
    }
    currentNodeElements.value = [];
    currentNodeElements.value.push(node);
    saveHistory('插入元素');
}

/**
 * 删除元素
 * @param node
 * @param index
 */
export const deleteNode = (node,index) => {
    for (let j = 0; j < drawData.value.nodeElements.length; j++) {
        let element = drawData.value.nodeElements[j];
        if(node.id === element.id){
            drawData.value.nodeElements.splice(j, 1);
        }
    }
    currentNodeElements.value.splice(index, 1);
    saveHistory('删除元素');
}
/**
 * 删除当前选中元素
 */
export const deleteCurrentNodeElements = () => {
    const ids = currentNodeElements.value.map(item=>{
        return item.id
    })
    const nodeElements = [];
    for (let j = 0; j < drawData.value.nodeElements.length; j++) {
        let element = drawData.value.nodeElements[j];
        if(!ids.includes(element.id)){
            nodeElements.push(element);
        }
    }
    drawData.value.nodeElements = nodeElements;
    currentNodeElements.value = [];
    saveHistory('删除当前选中元素');
}


/**
 * 拷贝一个对象
 * @param obj
 */
export function copyObj(obj) {
    return JSON.parse(JSON.stringify(obj));
}


/**
 * 复制当前选中的元素
 */
export const copyCurrentNodeElements = () => {
    const ids = currentNodeElements.value.map(item=>{
        return item.id
    })
    const nodeElements = [];
    const currentNodeElementsTemp = [];
    for (let j = 0; j < drawData.value.nodeElements.length; j++) {
        let element = drawData.value.nodeElements[j];
        nodeElements.push(element);
        if(ids.includes(element.id)){
            let obj = copyObj(element);
            let showNode = showNodeElements.value.find(item=>item.id === obj.id);
            obj.id = Math.random().toString(36).slice(2);
            obj.css.top += showNode.height;
            nodeElements.push(obj);
            currentNodeElementsTemp.push(obj);
        }
    }
    drawData.value.nodeElements = nodeElements;
    currentNodeElements.value = currentNodeElementsTemp;
    saveHistory('复制当前选中的元素');
}

/**
 * 复制当前元素到粘贴板
 */
export const copyCurrentNodeElementsToStickup = ()=>{
    if(currentNodeElements.value.length > 0){
        const copyData = copyObj(currentNodeElements.value);
        copyData.forEach((item)=>{
            delete item.width;
            delete item.height;
            delete item.id;
            delete item.moveData;
        })
        const data = {
            source: 'HadaCanvasPoster',
            content: copyData
        }
        uni.setClipboardData({
            data: JSON.stringify(data, null, 2),
            success: function () {
                uni.showToast({
                    title: '复制成功',
                });
            },
            fail:function () {
                uni.showToast({
                    title: '复制失败',
                });
            }
        });
    }
}

/**
 * 粘贴
 */
export const stickupData = ()=>{
    //粘贴数据
    var clipPromise = navigator.clipboard.readText();
    clipPromise.then(function(clipText){
        try {
            console.log('粘贴成功',clipText);
            const data = JSON.parse(clipText);
            if(data.source === 'HadaCanvasPoster'){
                data.content.forEach((item)=>{
                    item.id = Math.random().toString(36).slice(2);
                    item.css.left += 20;
                    item.css.top += 20;
                })
                let currentNodeElementIndex = getCurrentNodeElementIndex();
                drawData.value.nodeElements.splice(currentNodeElementIndex,0,...(data.content));
                draw();
            }
        }catch (e) {
            console.log('粘贴失败','数据格式不对',clipText);
        }
    });


}


const curShowNodes = computed(()=>{
    if(currentNodeElements.value.length === 0){
        return [];
    }
    const map = {};
    showNodeElements.value.forEach(item=>{
        map[item.id] = item;
    })
    return map;
})

/**
 * 位置操作  修改位置
 */
export const leftTopOperate = {

    /**
     * 水平居中
     */
    horizontalCenter(){
        if(currentNodeElements.value.length > 0){
            currentNodeElements.value.forEach(item=>{
                item.css.left = (drawData.value.width - curShowNodes.value[item.id].width)/2;
            })
            saveHistory('水平居中');
        }
    },

    /**
     * 垂直居中
     */
    verticalCenter(){
        if(currentNodeElements.value.length > 0){
            currentNodeElements.value.forEach(item=>{
                item.css.top = (drawData.value.height - curShowNodes.value[item.id].height)/2;
            })
            saveHistory('垂直居中');
        }
    },

    /**
     * 贴顶部
     */
    stickTop (){
        if(currentNodeElements.value.length > 0){
            currentNodeElements.value.forEach(item=>{
                item.css.top = 0;
            })
            saveHistory('贴顶部');
        }
    },

    /**
     * 贴底部
     */
    stickBottom(){
        if(currentNodeElements.value.length > 0){
            currentNodeElements.value.forEach(item=>{
                item.css.top = drawData.value.height - curShowNodes.value[item.id].height;
            })
            saveHistory('贴底部');
        }
    },

    stickLeft(){
        if(currentNodeElements.value.length > 0){
            currentNodeElements.value.forEach(item=>{
                item.css.left = 0;
            })
            saveHistory('贴左侧');
        }
    },

    stickRight(){
        if(currentNodeElements.value.length > 0){
            currentNodeElements.value.forEach(item=>{
                item.css.left = drawData.value.width - curShowNodes.value[item.id].width;
            })
            saveHistory('贴右侧');
        }
    }
}


/**
 * 对齐操作  多个元素之间
 */
export const alignOperate = {

    /**
     * 左对齐
     */
    left(){
        if(currentNodeElements.value.length > 1){
            //取到最左边的元素
            const minLeft = Math.min(...currentNodeElements.value.map(item=>item.css.left))
            currentNodeElements.value.forEach(item=>{
                item.css.left = minLeft;
            })
            saveHistory('左对齐');
        }
    },
    /**
     * 右对齐
     */
    right(){
        if(currentNodeElements.value.length > 1){
            //取到最右边的元素
            const maxRight = Math.max(...currentNodeElements.value.map(item=>item.css.left + curShowNodes.value[item.id].width))
            currentNodeElements.value.forEach(item=>{
                item.css.left = maxRight - curShowNodes.value[item.id].width;
            })
            saveHistory('右对齐');
        }
    },
    /**
     * 居中对齐
     */
    horizontalCenter(){
        if(currentNodeElements.value.length > 1) {
            //取到左边位置
            const minLeft = Math.min(...currentNodeElements.value.map(item => item.css.left));

            //取到右边位置
            const maxLeft = Math.max(...currentNodeElements.value.map(item => item.css.left + curShowNodes.value[item.id].width));

            //计算对齐的中心点
            const centerLeft = minLeft + (maxLeft - minLeft) / 2;

            currentNodeElements.value.forEach(item => {
                item.css.left = centerLeft - curShowNodes.value[item.id].width / 2;
            })
            saveHistory('居中对齐');
        }
    },
    /**
     * 垂直对齐
     */
    verticalCenter(){
        if(currentNodeElements.value.length > 1){
            //取到最上边的位置
            const minTop = Math.min(...currentNodeElements.value.map(item=>item.css.top))

            //取到最下边的位置
            const maxTop = Math.max(...currentNodeElements.value.map(item=>item.css.top + curShowNodes.value[item.id].height))

            //计算对齐的中心点
            const centerTop = minTop + (maxTop - minTop)/2;

            currentNodeElements.value.forEach(item=>{
                item.css.top = centerTop - curShowNodes.value[item.id].height/2;
            })
            saveHistory('垂直对齐');
        }
    },
    /**
     * 上对齐
     */
    top(){
        if(currentNodeElements.value.length > 1){
            //取到最上边的元素
            const minTop = Math.min(...currentNodeElements.value.map(item=>item.css.top))
            currentNodeElements.value.forEach(item=>{
                item.css.top = minTop;
            })
            saveHistory('上对齐');
        }
    },
    /**
     * 下对齐
     */
    bottom(){
        if(currentNodeElements.value.length > 1){
            //取到最下边的元素
            const maxTop = Math.max(...currentNodeElements.value.map(item=>item.css.top + curShowNodes.value[item.id].height))
            currentNodeElements.value.forEach(item=>{
                item.css.top = maxTop - curShowNodes.value[item.id].height;
            })
            saveHistory('下对齐');
        }
    }

}

/**
 * 撤销
 */
export const undo = () => {
    if(curIndex.value === 0){
        return;
    }
    curIndex.value--;
    console.log(historyDrawData.value[curIndex.value],'quash');
    drawData.value = copyObj(historyDrawData.value[curIndex.value].data);
    currentNodeElements.value = [];
    draw();
}
/**
 * 重做
 */
export const redo = () => {
    if(curIndex.value >= historyDrawData.value.length -1){
        return;
    }
    curIndex.value++;
    drawData.value = historyDrawData.value[curIndex.value].data;
    draw();
}

/**
 * 重做
 */
export const historyTo = (index) => {
    curIndex.value = index;
    drawData.value = historyDrawData.value[curIndex.value].data;
    draw();
}


//导入数据
export const importData=()=>{
    ElMessageBox.prompt('','导入数据',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入导入的数据',
    }).then(res=>{
        if(res){
            drawData.value = JSON.parse(res.value);
            drawData.value.nodeElements.forEach(item => {
                item.id = Math.random().toString(36).slice(2)
            })
            draw();
        }
    })
}

export const clearAll = () => {
    drawData.value.nodeElements = [];
    currentNodeElements.value = [];
    draw();
}
